package list;

import java.util.Comparator;
import java.util.Set;

public class OrdenedList<T>{
	
	private class Node<P>{
		private P elem;
		private Node<P> next;
		 
		public Node(P elem, Node<P> next){
			this.elem = elem;
			this.next = next;
		}
	}

	private int size;
	private Comparator<T> comp;
	private Node<T> head;
	private Node<T> last;
	
	public OrdenedList(Comparator<T> comp){
		size = 0;
		this.comp = comp;
		head = new Node<T>(null, null);
		last = head;
	}
	
	public OrdenedList( Set<T> elems, Comparator<T> comp){
		size = 0;
		this.comp = comp;
		head = new Node<T>(null, null);
		last = head;
		for(T elem: elems){
			add(elem);
		}
	}
	
	public void  add(T elem){
		Node<T> aux = head.next;
		Node<T> prevaux = head;
		while(aux != null){
			if(comp.compare(aux.elem, elem) == 1){
				Node<T> node = new Node<T>(elem, aux);
				prevaux.next = node;
				break;
			}
			prevaux = aux;
			aux =aux.next;
		}
	}
	
	public T remove(){
		if(head.next != null){
			T elem = head.next.elem;
			head.next = head.next.next;
			size--;
			return elem;
		}
		return null;
	}
	
	public void remove(T elem){
		Node<T> aux = head.next;
		Node<T> preaux = head;
		while(aux != null){
			if(comp.compare(aux.elem, elem) < 0) break;
			if(comp.compare(aux.elem, elem) == 0){
				preaux.next = aux.next;
				size--;
			}
			preaux = aux;
			aux = aux.next;
		}
	}	
	
	public boolean searchFor(T elem){
		Node<T> aux = head.next;
		while(aux != null){
			if(comp.compare(aux.elem, elem) == 0)
				return true;
			if(comp.compare(aux.elem, elem) < 0)
				return false;
			aux = aux.next;
		}
		return false;		
	}
	
	public OrdenedList<T> copy(){
		OrdenedList<T> l = new OrdenedList<T>(this.comp);
		Node<T> aux = head.next;
		while(aux != null){
			l.add(aux.elem);
		}
		return l;
	}

}
